/*
 * @Descripttion:
 * @Author: yuxi
 * @Date: 2021-01-22 23:41:56
 * @LastEditors: yuxi
 * @LastEditTime: 2023-08-03 20:48:57
 */
// import Vue from 'vue'
import axios from 'axios'
import {
  VueAxios
} from './axios'
import Message from 'element-ui'
const xsrfHeaderName = 'Authorization'
const isUni = !!window.uni

axios.defaults.timeout = 5000
axios.defaults.withCredentials = true
axios.defaults.xsrfHeaderName = xsrfHeaderName
axios.defaults.xsrfCookieName = xsrfHeaderName

// isUni = true
// 创建 axios 实例
const service = axios.create({
  baseURL: 'http://124.71.66.148:18090/api', // process.env.VUE_APP_BASE_API,
  timeout: 60000 // 请求超时时间
})

export function getToken () {
  if (isUni) {
    let item = localStorage.getItem(xsrfHeaderName)
    try {
      item = JSON.parse(item)
      if (item) {
        if (item.expires > new Date().getTime()) {
          return item.token
        } else {
          return null
        }
      }
    } catch (e) {
      return null
    }
  } else {
    return null
  }
}

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      Message.error(data.message)
    }
    if (error.response.status === 401) {
      Message.error('Authorization verification failed') 
    }
    error.message = error.response.data.msg || error.message
  }
  return Promise.reject(error)
}
// request interceptor
service.interceptors.request.use(config => {
  if (isUni) {
    config.headers['Authorization'] = getToken()
  }
   
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
} 